<?php
/**
 * 数组格式化
 * @param array $data
 * @param string $field
 * @return array|bool
 */
function array_format(array $data,string $field='id') {
    if (empty($data) || empty($field)) {
        return false;
    }

    $result = [];
    foreach ( $data as $val ) {
        $result[$val[$field]] = $val;
    }
    return $result;
}


/**
 * 数组格式化[分组]
 * @param array $data
 * @param string $field
 * @return array|bool
 */
function array_group(array $data,string $field='id') {
    if (empty($data) || empty($field)) {
        return false;
    }

    $result = [];
    foreach ( $data as $val ) {
        $key = is_object($val) ? $val->$field : $val[$field];
        $result[$key][] = $val;
    }
    return $result;
}


/**
 * 将数组格式化为树形结构
 * @param array $list
 * @param string $pk
 * @param string $pid
 * @param string $child
 * @param int $root
 * @param string $key
 * @return array
 */
function array_to_tree(array $list, string $pk = 'id', string $pid = 'pid', string $child = '_child', int $root = 0, $key = '') {
    // 创建Tree
    $tree = array();
    if (is_array ( $list )) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ( $list as $k => $data ) {
            $refer [$data [$pk]] = & $list [$k];
        }

        foreach ( $list as $k => $data ) {
            // 判断是否存在parent
            $parentId = $data [$pid];
            if ($root == $parentId) {
                if ($key != '') {
                    $tree [$data [$key]] = & $list [$k];
                } else {
                    $tree[] = & $list [$k];
                }
            } else {
                if (isset ( $refer [$parentId] )) {
                    $parent = & $refer [$parentId];
                    if ($key != '') {
                        $parent [$child] [$data [$key]] = & $list [$k];
                    } else {
                        $parent [$child] [] = & $list [$k];
                    }
                }
            }
        }
    }
    return $tree;
}

/**
 * @param $time
 * @return bool|string
 * @author: lxy
 * @time: 2020/6/16 3:13 下午
 * @流程:
 */
function Sec2Time($time){
    if(is_numeric($time)){
        $value = array(
            "years" => 0, "days" => 0, "hours" => 0,
            "minutes" => 0, "seconds" => 0,
        );
        if($time >= 31556926){
            $value["years"] = floor($time/31556926);
            $time = ($time%31556926);
        }
        if($time >= 86400){
            $value["days"] = floor($time/86400);
            $time = ($time%86400);
        }
        if($time >= 3600){
            $value["hours"] = floor($time/3600);
            $time = ($time%3600);
        }
        if($time >= 60){
            $value["minutes"] = floor($time/60);
            $time = ($time%60);
        }
        $value["seconds"] = floor($time);
        return $value["years"] ."年". $value["days"] ."天"." ". $value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";

    }else{
        return  false;
    }
}